<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2018/4/3
 * Time: 下午4:12
 */

namespace App\Http\Controllers\Traits;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

trait PassportProxyTrait
{
    /**
     * 获取Token
     * @return mixed
     */
    public function oAuthToken()
    {
        $client = new Client();

        try {
            $url = request()->root() . '/oauth/token';

            $params = array_merge(config('passport.proxy'), [
                'username' => request('username'),
                'password' => request('password'),
            ]);

            $response = $client->request('POST', $url, ['form_params' => $params]);

            if ($response->getStatusCode() !== 401) {
                return json_decode($response->getBody()->getContents(), true);
            }
        } catch (RequestException $exception) {
            throw new UnauthorizedHttpException('Challenge','请求失败，服务器错误');
        }

        throw new UnauthorizedHttpException('Challenge','账号或密码错误');
    }
}